package com.qiantu.phone.ui.fragment;

import static com.qiantu.phone.ui.fragment.device.BaseDeviceFragment.STATUS;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLMusicDBManager;
import com.qiantu.api.entity.MusicDaoBean;
import com.qiantu.api.entity.MusicListBean;
import com.qiantu.api.entity.MusiclikeListBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @Description: 当前播放音乐列表
 * @Time:  2023年1月30日
 */
public class MusicListFragment extends AppFragment<AppActivity>{
    private String serialNo;
    private int count = -1;  //当前播放歌曲下标
    private RecyclerView music_recyclerview;
    private TextView music_num;
    private TextView tv_top_name;
    private ImageView music_details;
    private CheckBox checkbox_music;
    private MusiclistAdapter musiclistAdapter;
    private String songname;
    private String music_name;
    private boolean ifscene = false;
    private String dialog_sign;
    private int type;
    private List<MusicDaoBean> getmusicbean = new ArrayList<>();

    public interface MusicListInterface{
        public void sendValue(String musicid,String musicName, String songpicurl);
    }
    private MusicListInterface musicListInterface;

    public static MusicListFragment newInstance(String serialNo, String songname, int type,String music_name,String dialog_sign) {
        MusicListFragment fragment = new MusicListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("serialNo",serialNo);
        bundle.putString("songname",songname);
        bundle.putString("music_name",music_name);
        bundle.putInt("type",type);
        bundle.putString("dialog_sign",dialog_sign);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_music_list;
    }

    @Override
    protected void initView() {
        music_recyclerview = findViewById(R.id.music_Recyclerview);
        music_num = findViewById(R.id.music_num);
        tv_top_name = findViewById(R.id.tv_top_name);
        ifscene = dialog_sign.equals("deviceDialog");
        initAdapter();
    }

    private void initsqlgetMusic() {
        getmusicbean = LLMusicDBManager.getInstance(getContext()).getmusicbean();
        getMusic();
    }


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Bundle arguments = getArguments();
        if (arguments!=null){
            serialNo = arguments.getString("serialNo");
            songname = arguments.getString("songname");
            music_name = arguments.getString("music_name");
            dialog_sign = arguments.getString("dialog_sign");
            type = arguments.getInt("type",0);
        }
        musicListInterface = (MusicListInterface) getActivity();
    }

    @Override
    protected void initData() {
        initsqlgetMusic();
    }

    private void initAdapter() {
        musiclistAdapter = new MusiclistAdapter();
        music_recyclerview.setAdapter(musiclistAdapter);
        music_recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        if (!ifscene){
            musiclistAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    SwitchMusicOperation(getmusicbean.get(position).getMusicID());
                    count = position;
                    musiclistAdapter.notifyDataSetChanged();
                }
            });
        }
    }


    //获取播放音乐列表
    private void getMusic() {
        LLHttpManager.getMusicList(this,serialNo,new HttpCallback<HttpData<MusicListBean>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<MusicListBean> result) {
                super.onSucceed(result);
                if (result.getData().getMiguMusicDtos().size() > getmusicbean.size()){
                    for (MusicListBean.MiguMusicDtos miguMusicDto : result.getData().getMiguMusicDtos()) {
                        MusicDaoBean musicDaoBean = new MusicDaoBean(null,miguMusicDto.getMusicName(),miguMusicDto.getSingerName(),false,miguMusicDto.getMusicID());
                        LLMusicDBManager.getInstance(getContext()).putbean(musicDaoBean);
                    }
                }else {
                    LLMusicDBManager.getInstance(getContext()).deleteAll();
                    for (MusicListBean.MiguMusicDtos miguMusicDto : result.getData().getMiguMusicDtos()) {
                        MusicDaoBean musicDaoBean = new MusicDaoBean(null,miguMusicDto.getMusicName(),miguMusicDto.getSingerName(),false,miguMusicDto.getMusicID());
                        LLMusicDBManager.getInstance(getContext()).putbean(musicDaoBean);
                    }
                }
                getmusicbean = LLMusicDBManager.getInstance(getContext()).getmusicbean();
                getMusiclike();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    private void updataview() {
        if (getmusicbean.size()!=0 && getmusicbean!=null){
            music_num.setText("（共"+getmusicbean.size()+"首歌曲）");
        }else {
            music_num.setText("（共"+"0首歌曲）");
        }
        for (int i = 0; i < getmusicbean.size(); i++) {
            if (getmusicbean.get(i).getMusic_name().equals(songname)){
                count = i;
            }
        }
    }


    private class MusiclistAdapter extends BaseQuickAdapter<MusicDaoBean, BaseViewHolder>{

        public MusiclistAdapter() {
            super(R.layout.item_music_list);
        }

        @Override
        public void setNewData(@Nullable List<MusicDaoBean> data) {
            super.setNewData(data);
        }

        @Override
        public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            holder.setText(R.id.music_id,position+1+"、");
            TextView music_name = holder.getView(R.id.music_name);
            TextView singer_name = holder.getView(R.id.singer_name);
            if (position==count){
                music_name.setTextColor(R.attr.themeColor);
                singer_name.setTextColor(R.attr.themeColor);
                checkbox_music.setChecked(true);
            }else {
                music_name.setTextColor(Color.parseColor("#536077"));
                singer_name.setTextColor(Color.parseColor("#989FAD"));
                checkbox_music.setChecked(false);
            }
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, MusicDaoBean item) {
            holder.setText(R.id.music_name,item.getMusic_name());
            holder.setText(R.id.singer_name,item.getSinger_name());
            ImageView music_like = holder.getView(R.id.music_like);
            music_details = holder.getView(R.id.music_details);
            checkbox_music = holder.getView(R.id.checkbox_music);
            music_like.setSelected(item.getIflike());
            music_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    music_like.setSelected(!music_like.isSelected());
                    item.setIflike(music_like.isSelected());
                    LLMusicDBManager.getInstance(getContext()).putbean(item);
                    getSetFavouritemusic(music_like.isSelected(),item.getMusicID());

                }
            });
            if(ifscene){
                music_like.setVisibility(View.GONE);
                music_details.setVisibility(View.GONE);
                checkbox_music.setVisibility(View.VISIBLE);
                checkbox_music.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        count = holder.getPosition();
                        musicListInterface.sendValue(item.getMusicID(),item.getMusic_name(),"");
                        notifyDataSetChanged();
                    }
                });
            }
        }
    }

    //收藏歌曲列表
    private void getMusiclike() {
        LLHttpManager.getfavouritemusicinfo(this,serialNo,new HttpCallback<HttpData<MusiclikeListBean>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<MusiclikeListBean> result) {
                super.onSucceed(result);
                ArrayList<MusiclikeListBean.MusiclikeList> musiclikeLists = result.getData().getMusiclikeLists();
                for (MusiclikeListBean.MusiclikeList musiclikeList : musiclikeLists) {
                    for (MusicDaoBean musicDaoBean : getmusicbean) {
                        if (musicDaoBean.getMusicID().equals(musiclikeList.getMusicId())){
                            musicDaoBean.setIflike(true);
                            LLMusicDBManager.getInstance(getContext()).putbean(musicDaoBean);
                        }
                    }
                }

                musiclistAdapter.setNewData(getmusicbean);
                updataview();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    //收藏歌曲
    private void getSetFavouritemusic(Boolean isFavourite,String musicID) {
        String[] musicIDS=new String[]{musicID};
        LLHttpManager.getSetFavouriteMusic(this,serialNo,musicIDS,isFavourite,new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    //切歌
    private void SwitchMusicOperation(String musicID) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> statusMap=new HashMap<>();
        map.put("songid",musicID);
        statusMap.put(STATUS,map);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(),serialNo,statusMap,new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                finish();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }
}